package service

import (
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"
	"video-srv/basic/config"
	__ "video-srv/basic/proto/rpc"
	"video-srv/handler/model"
)

type VideoServer struct {
	__.UnimplementedVideoServer
}

func (s *VideoServer) PublishVideo(_ context.Context, in *__.PublishVideoReq) (*__.PublishVideoResp, error) {
	video := model.Video{
		UserId: int(in.UserId),
		Title:  in.Title,
		Image:  in.Image,
		Refer:  in.Refer,
	}
	err := video.PublishVideo(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.PublishVideoResp{
		VideoId: int64(video.ID),
	}, nil
}
func (s *VideoServer) CheckVideo(_ context.Context, in *__.CheckVideoReq) (*__.CheckVideoResp, error) {
	checkVideo := model.CheckVideo{
		UserId:  int(in.UserId),
		VideoId: int(in.VideoId),
		Status:  int(in.Status),
		Reason:  in.Reason,
	}
	err := checkVideo.CheckVideo(config.DB)
	if err != nil {
		return nil, err
	}
	var video model.Video
	err = video.UpdateVideoStatus(config.DB, int(in.VideoId), int(in.Status))
	if err != nil {
		return nil, err
	}
	return &__.CheckVideoResp{
		CheckVideoId: int64(checkVideo.ID),
	}, nil
}
func (s *VideoServer) GetVideoList(_ context.Context, in *__.GetVideoListReq) (*__.GetVideoListResp, error) {
	var Videos model.Video
	list, err := Videos.GetVideoList(config.DB)
	if err != nil {
		return nil, err
	}
	var wg sync.WaitGroup
	for _, video := range list {
		wg.Add(1)
		go func(video *__.VideoItem) {
			defer wg.Done()
			// Build the request body.
			data, err := json.Marshal(video)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			req := esapi.IndexRequest{
				Index:      "video_1030",
				DocumentID: strconv.Itoa(int(video.Id)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			res, err := req.Do(context.Background(), config.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()
		}(video)
	}
	wg.Wait()
	return &__.GetVideoListResp{
		List: list,
	}, nil
}
func (s *VideoServer) GetVideoListById(_ context.Context, in *__.GetVideoListByIdReq) (*__.GetVideoListByIdResp, error) {
	var video model.Video
	info, err := video.GetVideoListById(config.DB, int(in.VideoId))
	if err != nil {
		return nil, err
	}
	return &__.GetVideoListByIdResp{
		Id:           int64(video.ID),
		Title:        info.Title,
		Image:        info.Image,
		Refer:        info.Refer,
		Status:       info.Status,
		AreaName:     info.AreaName,
		CategoryName: info.CategoryName,
		ChannelName:  info.ChannelName,
	}, nil
}
